<?php
namespace app\models;

use Yii;
use yii\base\Model;

/**
 * 管理员登录表单
 *
 * Class ManagerLoginForm
 * @package app\models
 *
 * @property Manager $manager 管理员
 */
class ManagerLoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    /* @var $_manager Manager */
    private $_manager = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            ['rememberMe', 'boolean'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * 验证登录密码
     * @param string $attribute
     * @param mixed $params
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $manager = $this->getManager();
            if (!$manager || !$manager->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或密码错误。');
            }
        }
    }

    /**
     * 登录操作
     * @return bool
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->manager->login($this->getManager(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * 根据登录参数返回管理员Model
     * @return false|Manager
     */
    public function getManager()
    {
        if ($this->_manager === false) {
            $this->_manager = Manager::find()->where(['status'=>[Manager::STATUS_ACTIVE, Manager::STATUS_STOPED], 'username'=>$this->username])->one();
            if (!empty($this->_manager) && $this->_manager->status == Manager::STATUS_STOPED) {
                $this->addError('username', '此账号已停用。');
            }
        }
        return $this->_manager;
    }
}
